package com.MetaverseMaker.UniverseFarm.controller;

import com.MetaverseMaker.UniverseFarm.dto.MyCart;
import com.MetaverseMaker.UniverseFarm.dto.MyMessage;
import com.MetaverseMaker.UniverseFarm.entity.Cart;
import com.MetaverseMaker.UniverseFarm.entity.SoilInfo;
import com.MetaverseMaker.UniverseFarm.entity.UserInfo;
import com.MetaverseMaker.UniverseFarm.service.IUserInfoService;
import com.MetaverseMaker.UniverseFarm.service.impl.CartInfoServiceImpl;
import com.MetaverseMaker.UniverseFarm.service.impl.OrderInfoServiceImpl;
import com.MetaverseMaker.UniverseFarm.service.impl.SoilInfoServiceImpl;
import org.apache.commons.collections.bag.SynchronizedSortedBag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: wanghuiqian
 * @Date: 2021/12/25 - 12 - 25 - 14:09
 * @Description: com.MetaverseMaker.UniverseFarm.controller
 * @version: 1.0
 */
@Controller
public class CartController {
    @Resource
    private CartInfoServiceImpl cartInfoService;
    @Resource
    private SoilInfoServiceImpl soilInfoService;
    @Autowired
    private OrderInfoServiceImpl orderInfoService;
    @Autowired
    private IUserInfoService iUserInfoService;

    /**
     * 获取购物车信息
     *
     * @param session
     * @return
     */
    @RequestMapping("/findCart")
    @ResponseBody
    public MyCart findCart(HttpSession session) {
        MyCart mv = new MyCart();
        List<Cart> cartList = new ArrayList<>();
        Map<Integer, Cart> cartMap = new HashMap<>();
        List<SoilInfo> list = new ArrayList<>();
        List<Integer> list1 = new ArrayList<>();
        Double allMoney = 0.0;
        int totalCount = 0;

        BigDecimal totalMoney = BigDecimal.valueOf(0);

        try {
            cartMap = cartInfoService.getItems();
            totalCount = cartInfoService.getTotalCount();
            totalMoney = cartInfoService.getTotalMoney();

        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(cartMap);
        for (Map.Entry<Integer, Cart> item : cartMap.entrySet()) {
            Cart cart = item.getValue();
            cartList.add(cart);
            allMoney += Double.parseDouble(cart.getTotalMoney());
        }
        mv.setAllMoney(allMoney);
        session.setAttribute("cartMap", cartMap);
        session.setAttribute("totalCount", totalCount);
        mv.setCartList(cartList);
        session.setAttribute("totalMoney", totalMoney);
//        mv.addObject("totalMoney",totalMoney);
        mv.setCartMap(cartMap);
        session.setAttribute("cartList", cartList);
//        mv.addObject("cartList",cartList);
//        mv.setViewName("cart");
        mv.setTotalCount(totalCount);
        Double money = totalMoney.doubleValue();
        mv.setTotalMoney(money);
        System.out.println(1111);
        return mv;
    }

    /**
     * 删除购物车指定的商品
     *
     * @param id
     * @return
     */
    @RequestMapping("/deleteCart")
    public MyMessage deleteCart(HttpSession session, int id) {

        MyMessage message=new MyMessage();
        try {
            cartInfoService.deleteItem(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        message.setFlag(1);
//        LoggerUtil.setINFOLoggers("当前用户删除了商品:"+deleteCartID);
//        LoggerUtil.setINFOLoggers("当前购物车里的数量："+session.getAttribute("totalCount"));
        return message;
    }


    /**
     * 清空购物车
     *
     * @return
     */
    @RequestMapping("/clearCart")
    @ResponseBody
    public MyMessage clearCart() {
        MyMessage message=new MyMessage();
        try {
            cartInfoService.clear();
            System.out.println("clear");
        } catch (Exception e) {
            e.printStackTrace();
        }
        message.setFlag(1);
        return message;
//        LoggerUtil.setINFOLoggers("当前用户清空了购物车！");
//        return "redirect:/findCart";
    }

    /**
     * 添加商品到购物车中
     *
     * @param soilinfoid
     * @param session
     * @return
     */
    @RequestMapping("/addCart")
    @ResponseBody
    public MyCart addCart(int soilinfoid, HttpSession session) {
        SoilInfo soilInfo = new SoilInfo();
        List<Integer> list = new ArrayList<>();
        MyCart ms = new MyCart();
        try {
            soilInfo = soilInfoService.findSoilInfoById(soilinfoid);
            list.add(soilinfoid);
            cartInfoService.addItem(soilInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (session.getAttribute("list") == null) {
            session.setAttribute("list", list);
            session.setAttribute("totalCount", 1);
            ms.setMsg("添加成功");
            return ms;
        } else {
            List<Integer> list1 = (List<Integer>) session.getAttribute("list");
            boolean f = false;
            for (int i = 0; i < list1.size(); i++) {
                if (soilinfoid == list1.get(i)) {
                    f = true;
                    break;
                }
            }
            if (f) {
                ms.setMsg("已在购物车");
                return ms;
            } else {
                list1.add(soilinfoid);
                session.setAttribute("list1", list1);
                ms.setMsg("添加成功");
                return ms;
            }
        }

        /*手动更新session*/
//            session.setAttribute("totalCount", (int) session.getAttribute("totalCount") + 1);
//            int cartTotalCount = (int) session.getAttribute("totalCount");
//            System.out.println("购物车里的数量：" + cartTotalCount);

//        LoggerUtil.setINFOLoggers("当前用户新增了商品"+dishesId+"到购物车中..");
//        LoggerUtil.setINFOLoggers("购物车里当前的数量："+cartTotalCount);
//        ms.setMsg("添加成功");
//            return ms;
    }

    /**
     * 更新购物车的信息
     *
     * @param cartId
     * @param count
     * @param session
     * @return
     */
    @RequestMapping("/updateCart")
    @ResponseBody
    public List updateCart(int cartId, int count, HttpSession session) {
        System.out.println("CartId:" + cartId);
        System.out.println("Count:" + count);
        try {
            cartInfoService.updateItem(cartId, count);
        } catch (Exception e) {
            e.printStackTrace();
        }

        /*修改当前的购物车中选定的的价格*/
        List<Cart> cartList = (List<Cart>) session.getAttribute("cartList");
        int cartTotalCount = 0;
        int cartTotalMoney = 0;
        int currentCartMoney = 0;
        for (Cart cart : cartList) {
            if (cart.getId() == cartId) {
                cart.setCount(count + "");/*将前台输入过来的数量替换*/
                cart.setTotalMoney(Integer.parseInt(cart.getPrice()) * count + "");
                currentCartMoney = Integer.parseInt(cart.getTotalMoney());
                break;
            }

        }

        for (Cart cart : cartList) {
            cartTotalMoney += Integer.parseInt(cart.getTotalMoney());
            cartTotalCount += Integer.parseInt(cart.getCount());
        }


        System.out.println("当前商品数量=" + cartTotalCount);
        System.out.println("当前商品的总价格 = " + cartTotalMoney);
        session.setAttribute("cartList", cartList);


        session.setAttribute("totalMoney", cartTotalMoney + "");
        System.out.println("当前购物车里面的总价格=" + cartTotalMoney);

        /*更新session*/
        session.setAttribute("totalCount", cartTotalCount);
        System.out.println("购物车里的数量：" + cartTotalCount);

        List<String> cartInfoList = new ArrayList<>();
        cartInfoList.add(cartTotalCount + "");/*购物车的总数量*/
        cartInfoList.add(currentCartMoney + "");/*当前的商品的价格*/
        cartInfoList.add(cartTotalMoney + "");/*购物车的总价格*/
        return cartInfoList;
    }

    //    @RequestMapping("/success")
//    public ModelAndView success(){
//        ModelAndView mv= new ModelAndView();
//        System.out.println("购买成功！");
//        mv.setViewName("cart.jsp");
//        return mv;
//    }
    @RequestMapping("/pay")
    @ResponseBody
    public MyMessage pay(Double paymoney, HttpSession session) throws Exception {
        System.out.println(paymoney);
        Map<Integer, Cart> cartMap =(Map<Integer, Cart>) session.getAttribute("cartMap");
        MyMessage message = new MyMessage();
        System.out.println("长度为"+cartMap.size());
        if (session.getAttribute("loginuser") != null) {
            UserInfo userInfoSession = (UserInfo) session.getAttribute("loginuser");
            //session直接获得的userInfo中的数据都是旧的，充值后不会更新所以得去重新去数据库查
            UserInfo userInfo = iUserInfoService.findUserById(userInfoSession.getUserId());
            System.out.println("钱：:"+userInfo.getUserIntegral());
            if (userInfo.getUserIntegral() > paymoney) {
                message.setFlag(1);
                userInfo.setUserIntegral(userInfo.getUserIntegral() - paymoney);
                iUserInfoService.updateUser(userInfo);
                System.out.println(cartMap.size());
                for (Map.Entry<Integer, Cart> item : cartMap.entrySet()) {
                    Cart cart = item.getValue();
                    System.out.println(cart);
                    int soilid=cart.getId();
                    SoilInfo soilInfo=soilInfoService.findSoilInfoById(soilid);
                    int userid=soilInfo.getSoilUserid();
                    System.out.println("id为"+userid);
                    soilInfo.setSoilUserid(userInfo.getUserId());
                    soilInfoService.update(soilInfo);
                    UserInfo userInfo1=iUserInfoService.findUserById(userid);
                    userInfo1.setUserIntegral(userInfo1.getUserIntegral()+Double.parseDouble(cart.getTotalMoney()));
                    iUserInfoService.updateUser(userInfo1);
                }
                orderInfoService.saveOrder(cartInfoService, userInfo.getUserId());
                message.setMsg("购买成功，请耐心等待到货");
                return message;
            } else {
                message.setFlag(2);
                message.setMsg("余额不足");
                return message;
            }
        } else {
            message.setFlag(0);
            message.setMsg("未登录，请登录后操作");
            return message;
        }
    }
}